package com.gl.doc.support;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;

/**
 * xml帮助工具类
 */
public class XmlSupport {

    /**
     * 添加一段xml
     *
     * @param xmlFile xml文件
     * @param xml     xml字符串
     * @throws Exception 异常
     */
    public static void addElement(File xmlFile, String xml) throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(xmlFile);
        Element rootElement = document.getRootElement();
        rootElement.addElement(xml);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }

    /**
     * 保存文档
     *
     * @param document word文档
     * @param xmlFile  xml对象
     * @throws Exception 异常
     */
    public static void writer(Document document, File xmlFile) throws Exception {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}
